package com.example.myapplicationktkt2.mini


import android.os.Handler
import android.os.Looper
import android.webkit.JavascriptInterface
import android.webkit.WebView
import com.example.myapplicationktkt2.log.Logger
import org.json.JSONObject


class MiniAppBridge(private val webView: WebView) {


    /**
     * 与主线程(UI线程)关联的Handler，用于发布需要在主线程执行的任务
     */
    private val mainHandler = Handler(Looper.getMainLooper())


    /**
     * 处理从JavaScript发送过来的消息
     *
     * @param json 包含调用信息的JSON字符串，格式应包含id、method和params字段
     */
    // JS 调用这个函数：window.__nativeBridge.postMessage(JSON.stringify(payload))
    @JavascriptInterface
    fun postMessage(json: String) {
        // 在工作线程解析并处理
        Thread {
            try {
                val obj = JSONObject(json)
                val id = obj.optString("id")
                val method = obj.optString("method")
                val params = obj.optJSONObject("params")
                Logger.d("MiniAppBridge", "postMessage: $json")

                // 根据方法名分发处理不同的native调用
                when (method) {
                    "native.echo" -> {
                        val message = params?.optString("message") ?: ""
                        val result = JSONObject().put("echo", message)
                        // 日志输出
                        Logger.d("MiniAppBridge", "Echo method called with message: $message")
                        respondSuccess(id, result)
                    }

                    "native.getTime" -> {
                        val result = JSONObject().put("time", System.currentTimeMillis())
                        Logger.d("MiniAppBridge", "getTime method called")
                        respondSuccess(id, result)
                    }

                    else -> {
                        Logger.w("MiniAppBridge", "Unknown method: $method")
                        respondError(id, 404, "method_not_found")
                    }
                }

            } catch (e: Exception) {
                Logger.e("MiniAppBridge", "Error processing message: ${e.message}")
                e.printStackTrace()
            }
        }.start()
    }


    /**
     * 向JavaScript端发送成功响应
     *
     * @param id 请求ID，用于匹配响应与请求
     * @param result 包含执行结果的JSONObject
     */
    private fun respondSuccess(id: String, result: JSONObject) {
        val resp = JSONObject()
        resp.put("id", id)
        resp.put("status", 0)
        resp.put("result", result)
        Logger.d("MiniAppBridge", "Responding with success: $result")
        postToJs(resp)
    }


    /**
     * 向JavaScript端发送错误响应
     *
     * @param id 请求ID，用于匹配响应与请求
     * @param code 错误代码
     * @param message 错误信息描述
     */
    private fun respondError(id: String, code: Int, message: String) {
        val resp = JSONObject()
        resp.put("id", id)
        resp.put("status", code)
        resp.put("error", message)
        Logger.d("MiniAppBridge", "Responding with error: $code - $message")
        postToJs(resp)
    }


    /**
     * 将消息发送到JavaScript端
     *
     * @param obj 需要传递给JavaScript的JSONObject数据
     */
    private fun postToJs(obj: JSONObject) {
        val script =
            "window.dispatchEvent(new MessageEvent('message', {data: ${obj.toString()} }));"
        Logger.d("MiniAppBridge", "Posting to JS: $script")
        
        mainHandler.post {
            webView.evaluateJavascript(script, null)
        }
    }
}